import json


from django.http import HttpResponse
from django.shortcuts import render, render_to_response
from django.core.paginator import Paginator
# Create your views here.
from django.shortcuts import render,redirect
from django.contrib.auth import authenticate,login,logout
from django.contrib.auth.forms import UserCreationForm,UserChangeForm
from django.contrib.auth.decorators import login_required

from .ciyun import jb
from .utitl import MysqlHelper
from .models import*
#from comment.models import*
#from .forms import*

import time, datetime
#登陆和主页
mysqlhe=MysqlHelper()
def user_login(request):
    if request.method == 'POST':

        username = request.POST['user_name']
        password = request.POST['pwd']
        user = authenticate(request, username='lang',
                            password='li000000')
        ggsql = 'select * from gg  order by id desc '
        gglist = mysqlhe.get_all(ggsql)
        print(gglist)
        if username !='' and password!='':
            sql='select * from teachers where 账号="{0}" and 密码="{1}"'.format(username,password)
            print(sql)
            stu=mysqlhe.get_all(sql)
            print(stu)
            teacheruser=Teacher.objects.filter(tzh=username).first()


            if len(stu)==1:
                print(stu)
                request.session['stu']= stu[0]
                request.session['name'] = stu[0][2]
                request.session['id']=stu[0][1]
                if teacheruser.tpy=='1':


                    return render(request, 'admin1/index.html', {'vb': '', 'zd': '管理端','img':teacheruser.tid, 'name': stu[0],'gg':gglist[0]})

                else:
                    return render(request, 'teacher/index.html', {'vb': '','zd':'客户端','name': stu[0],'gg':gglist[0]})

            else:
                return render(request, 'teacher/login1.html', {'error': '账号不存在'})




            # print('*******************')
            # print(request.POST['type'])
        #     # 学生
        #     if request.POST['type1'] == 1:
        #         return render(request, 'teacher/login.html', {'error': '学生主页'})
        #     # print('*******************')
        #     # print(request.POST['type'])
        #     else:
        #         return render(request, 'teacher/login.html', {'error': '请选择角色121212'})
        #
        else:
            return render(request, 'teacher/login.html',{'error': '账号密码不为空'})
        user = authenticate(request, username=request.POST['user_name'],
                            password=request.POST['pwd'])
        print(request.POST['type'])


    else:
        return render(request,'teacher/login1.html')
# 注册
def register(request):
    if request.method == 'POST':
        tid=request.POST['tid']
        tzh = request.POST['tzh']
        tname=request.POST['tname']
        tpas=request.POST['tpas']
        tgender=request.POST['tgender']
        print('##############')
        Teacher.objects.create(tid=tid,tname=tname,tzh=tzh,tpas=tpas,tgender=tgender,tpy='0')
        return render(request, 'teacher/register.html',{'jg':'注册成功'})

    else:
        return render(request, 'teacher/register.html')
def register1(request):
    ssql="select num from num"
    snum=mysqlhe.get_all(ssql)[0][0]
   
    tsql="select count(*) as num from teachers where 类型='0'"
    tnum=mysqlhe.get_all(tsql)[0][0]
    print(snum,tnum)
    if snum>tnum:
        img = request.FILES.get('tpas')

        name1 = request.FILES.get('tpas').name

        file_name = './static/img/' + str(int(time.time())) + '.' + name1.split('.')[-1]  # 构造文件名以及文件路径
        urlname = 'static/img/' + str(int(time.time())) + '.' + name1.split('.')[-1]

        zh = request.POST['zh']
        pwd = request.POST['pwd']

        # lx=''

        tname = request.POST['tname']
        sql = "INSERT INTO teachers (账号,名字,密码,头像,类型) values ('{0}','{1}','{2}','{3}','0')".format(zh, tname, pwd,urlname)
        print(sql)
        mysqlhe.insert(sql)
        if name1.split('.')[-1] not in ['jpeg', 'jpg', 'png', 'gif']:
            return HttpResponse('输入文件有误')
        try:
            with open(file_name, 'wb+') as f:
                f.write(img.read())
        except Exception as e:
            print(e)
        return render(request, 'teacher/login1.html')
    else:
        return render(request, 'teacher/register.html',{'jg':'用户数量已达上线'})
def register2(request):
    stu=request.session.get('stu')
    img = request.FILES.get('tpas')
    imgsql=stu[6]
    zh=stu[2]
    pwd=stu[4]
    if img!=None:
        name1 = request.FILES.get('tpas').name
        print(name1, img.size)
        file_name = './static/img/' + str(int(time.time())) + '.' + name1.split('.')[-1]  # 构造文件名以及文件路径
        urlname = 'static/img/' + str(int(time.time())) + '.' + name1.split('.')[-1]
        if name1.split('.')[-1] not in ['jpeg', 'jpg', 'png', 'gif']:
            return HttpResponse('输入文件有误')
        try:
            with open(file_name, 'wb+') as f:
                f.write(img.read())
        except Exception as e:
            print(e)
        imgsql=urlname
    if 'tname' in request.POST:
        zh = request.POST['tname']

    if 'pwd' in request.POST:
        pwd = request.POST['pwd']


    sql = 'update teachers set 头像="{1}",名字="{2}",密码="{3}" where id={0}'.format(stu[0],imgsql,zh,pwd)
    print(sql)
    mysqlhe.update(sql)
    stu=mysqlhe.get_all('select * from teachers where id={0}'.format(stu[0]))



    return render(request, 'teacher/login1.html')
def xiugai(request):
    name = request.session.get("name")
    stu=request.session.get("stu")
    print(name,'$$$$$$$$$$$$$$$',stu)
    teacheruser = Teacher.objects.filter(tname=name).first()
    if len(stu)!=0:
        vb = '数据预览'
        if request.method == 'GET':
            city1=mysqlhe.get_all('select COUNT(*)as num ,onej from gj  group by onej ')
            city=[]
            for i in city1:
                city.append(i[1])
            # city=['1','2','3']
            # house=House.objects.all()
            house = mysqlhe.get_all(
                'select b.imgurl, b.name, b.hx, b.price, b.mj1, b.xqname, b.id from gj as b ')

            print(house)
            return render(request, 'teacher/gr.html',
                          {'zd':'客户端','vb': vb, 'name': stu,'imgurl':'static/img/meng.png', 'zh': teacheruser.tzh, 'tname': teacheruser.tname, 'tpas': "******",
                           'tgender': teacheruser.tgender, 'tid': teacheruser.tid,'city':city,'house':house})
        if request.method == 'POST':
            id = request.session.get("id")

            user_name=request.POST['user_name']
            if user_name!='':
                name=user_name
                request.session['name'] = user_name
                Teacher.objects.filter(id=id).update(tname=user_name)
            user_tpas=request.POST['user_tpas']
            if user_tpas!='':
                Teacher.objects.filter(id=id).update(tpas=user_tpas)

            return render(request, 'teacher/gr.html',{'zd':'教师端','vb': vb, 'name': name, 'zh': teacheruser.tzh, 'tname': teacheruser.tname, 'tpas': "******",
                           'tgender': teacheruser.tgender, 'tid': teacheruser.tid,'jg':'成功'})
        else:
            print("*********************")
    else:
        return render(request, 'teacher/login1.html', {'error': '请登陆'})
def list(request):
    name = request.session.get("name")
    teacheruser = Teacher.objects.filter(tname=name).first()
    if teacheruser != None:
        vb = '数据管理'

        if request.method == 'GET':
            pindex=''
            book_list=[]
            paginator = Paginator(book_list, 5)
            page = paginator.page(pindex)  # 传递当前页的实例对象到前端



            return render(request, 'teacher/list.html',
                          {'zd': '', 'vb': vb, 'name': name, 'imgurl': 'static/img/meng.png', 'zh': teacheruser.tzh,
                           'tname': teacheruser.tname, 'tpas': "******",
                           'tgender': teacheruser.tgender, 'tid': teacheruser.tid,"page": page})
    else:
        return render(request, 'teacher/login1.html', {'error': '请登陆'})
# 数据
def list(request):
    name = request.session.get("name")
    teacheruser = Teacher.objects.filter(tname=name).first()
    if teacheruser != None:
        vb = '数据管理'

        if request.method == 'GET':
            return render(request, 'teacher/list.html',
                          {'zd': '', 'vb': vb, 'name': name, 'imgurl': 'static/img/meng.png', 'zh': teacheruser.tzh,
                           'tname': teacheruser.tname, 'tpas': "******",
                           'tgender': teacheruser.tgender, 'tid': teacheruser.tid})
    else:
        return render(request, 'teacher/login1.html', {'error': '请登陆'})
def lsit(request):
    result=""
    return HttpResponse(json.dumps(result,ensure_ascii=False),content_type="application/json,charset=utf-8")
def kestj(request):
    name = request.session.get("name")
    teacheruser = Teacher.objects.filter(tname=name).first()

    vb = '数据预览'
    mysqlhe=MysqlHelper()
    city1 = mysqlhe.get_all('select COUNT(*)as num ,onej from gj  group by onej ')
    city = []
    for i in city1:
        city.append(i[1])
    if request.method == 'GET':


        # city=['1','2','3']

        return render(request, 'teacher/gr.html',
                      {'zd': '客户端', 'vb': vb, 'name': name, 'imgurl': 'static/img/meng.png', 'zh': teacheruser.tzh,
                       'tname': teacheruser.tname, 'tpas': "******",
                       'tgender': teacheruser.tgender, 'tid': teacheruser.tid, 'city': city})
    if request.method == 'POST':
        lx=request.POST['lx']
        jg=request.POST['jg']
        print(lx,jg)
        if lx!='0':
            house = House.objects.filter(geju__contains=lx)


        return render(request, 'teacher/gr.html',
                      {'zd': '教师端', 'vb': vb, 'name': name, 'zh': teacheruser.tzh, 'tname': teacheruser.tname,
                       'tpas': "******",
                       'tgender': teacheruser.tgender, 'tid': teacheruser.tid, 'jg': '成功', 'house': house})
    else:
        return render(request, 'teacher/login1.html', {'error': '请登陆'})
def sc(request):
    stu = request.session.get("stu")
    vb = '我的收藏'
    if len(stu) != 0:
        if request.method == 'GET':
            city1 = mysqlhe.get_all('select COUNT(*)as num ,onej from gj  group by onej ')
            city = []
            for i in city1:
                city.append(i[1])
            house=mysqlhe.get_all('select b.imgurl,b.name,b.hx,b.price,b.mj1,b.xqname,b.id,a.lx from sc as a left join gj as b on a.sid=b.id  where a.lx="0" and a.uid={0}'.format(stu[0]))
            # print(house)
            return render(request, 'teacher/sc.html',{'zd': '客户端','vb': vb,'name': stu, 'city': city,'house':house})
    else:
        return render(request, 'teacher/login1.html', {'error': '请登陆'})
def psc(request):
    stu = request.session.get("stu")


    vb = '偏爱收藏'
    if len(stu) != 0:
        if request.method == 'GET':
            city1 = mysqlhe.get_all('select COUNT(*)as num ,onej from gj  group by onej ')
            city = []
            for i in city1:
                city.append(i[1])
            house=mysqlhe.get_all('select b.imgurl,b.name,b.hx,b.price,b.mj1,b.xqname,b.id,a.lx from sc as a left join gj as b on a.sid=b.id  where a.lx="1" and a.uid={0}'.format(stu[0]))
            print('select b.imgurl,b.name,b.hx,b.price,b.mj1,b.xqname,b.id,a.lx from sc as a left join gj as b on a.sid=b.id  where a.lx="1" and a.uid={0}'.format(stu[0]))
            return render(request, 'teacher/psc.html',{'zd': '客户端','vb': vb,'name': stu, 'city': city,'house':house})
    else:
        return render(request, 'teacher/login1.html', {'error': '请登陆'})
def jrsc(request):
    stu = request.session.get("stu")
    id=request.GET['id']
    cxsql="select * from sc where uid={0} and sid={1}".format(stu[0],id)
    if len(mysqlhe.get_all(cxsql))==0:
        sql="INSERT INTO sc ( uid, sid,lx)VALUES( {0}, {1},'0')".format(stu[0],id)
        mysqlhe.insert(sql)
    return HttpResponse('收藏成功')

def pjrsc(request):
    stu = request.session.get("stu")

    id=request.GET['id']
    cxsql="select * from sc where uid={0} and sid={1}".format(stu[0],id)
    print(cxsql)
    if len(mysqlhe.get_all(cxsql))==0:
        sql="INSERT INTO sc ( uid, sid,lx)VALUES( {0}, {1},'1')".format(stu[0],id)
        mysqlhe.insert(sql)
    return HttpResponse('收藏成功')
def qxsc(request):
    name = request.session.get("name")
    stu = request.session.get("stu")
    teacheruser = Teacher.objects.filter(tname=name).first()
    id = request.GET['id']
    sql = "DELETE FROM sc where uid={0} and sid={1}".format(stu[0],id)
    print(sql)
    mysqlhe.delete(sql)
    return HttpResponse('取消成功')
def cy(request):
    stu = request.session.get("stu")

    city1 = mysqlhe.get_all('select COUNT(*)as num ,onej from gj  group by onej ')
    city = []
    for i in city1:
        city.append(i[1])

    vb = '词云分析'
    if len(stu) != 0:
        cyname = mysqlhe.get_all('select name from gj  ')
        cytxt=''
        for i in cyname:
            cytxt=cytxt+i[0]
        t=jb(cytxt)

        return render(request, 'teacher/cy.html',{'zd': '客户端','vb': vb,'name': stu, 'city': city,'imgurl':'static/img/meng.png'})
    else:
        return render(request, 'teacher/login1.html', {'error': '请登陆'})
def cyt(request):
    name = request.session.get("name")
    

    city1 = mysqlhe.get_all('select COUNT(*)as num ,onej from gj  group by onej ')
    city = []
    for i in city1:
        city.append(i[1])
    teacheruser = Teacher.objects.filter(tname=name).first()
    vb = '词云分析'
    if teacheruser != None:
        onej=request.GET['id']
        cyname = mysqlhe.get_all('select name from gj where onej="{0}" '.format(onej))
        cytxt=''
        for i in cyname:
            cytxt=cytxt+i[0]
        t=jb(cytxt)

        return render(request, 'teacher/cy.html',{'zd': '客户端','vb': vb,'name': name, 'city': city,'imgurl':'static/img/meng.png'})
    else:
        return render(request, 'teacher/login1.html', {'error': '请登陆'})        
def diqu(request):
    stu = request.session.get("stu")

    city1 = mysqlhe.get_all('select COUNT(*)as num ,onej from gj  group by onej ')
    city = []
    for i in city1:
        city.append(i[1])

    vb = '地区分析'
    if len(stu) != 0:
        print('zheng')
        return render(request, 'teacher/diqu.html',
                      {'zd': '客户端', 'vb': vb, 'name': stu, 'city': city, 'imgurl': 'static/img/meng.png'})
    else:
        return render(request, 'teacher/login1.html', {'error': '请登陆'})
def fytj(request):
    stu = request.session.get("stu")

    city1 = mysqlhe.get_all('select COUNT(*)as num ,onej from gj  group by onej ')
    city = []
    for i in city1:
        city.append(i[1])

    vb = '房源推荐'
    if len(stu) != 0:
        house1 = mysqlhe.get_all(
            'select b.imgurl,b.onej,b.hx,b.price,b.mj1,b.xqname,b.id from sc as a left join gj as b on a.sid=b.id  where a.uid={0}'.format(
                stu[0]))
        print(len(house1))
        if len(house1)>5:
            house=[]
            print('2323')
            import random
            L1 = random.sample(range(0, len(house1)), 5)
            print(L1)
            for i in L1:


                house.append(house1[i])

        else:
            house=house1

        return render(request, 'teacher/tj.html',{'zd': '客户端','vb': vb,'name': stu, 'city': city,'house':house})
    else:
        return render(request, 'teacher/login1.html', {'error': '请登陆'})
def tongj(request):
    name = request.session.get("name")
    teacheruser = Teacher.objects.filter(tname=name).first()
    id=request.GET['id']
    if teacheruser != None:
        print("%%%%%%%",id)
        sql='select count(*) as num,twoj from gj where onej="{0}" group by twoj'.format(id)

        data1=mysqlhe.get_all(sql)
        z=[]
        h=[]
        for i in data1:
            z.append(i[0])
            h.append(i[1])
        # z=[19,21,26,24]
        #         # h=['渝中','九龙坡','江北','南岸']
        tj={'z':z,'h':h}

        dtsql='select url from dt where sheng="{0}"'.format(id)

        dtjson=((mysqlhe.get_all(dtsql))[0])[0]

        data = {'data': data1, 'tj': tj,"dtjson":dtjson}
        return HttpResponse(json.dumps(data))
    else:
        return render(request, 'teacher/login1.html', {'error': '请登陆'})
def jg(request):
    stu = request.session.get("stu")

    city1 = mysqlhe.get_all('select COUNT(*)as num ,onej from gj  group by onej ')
    city = []
    for i in city1:
        city.append(i[1])

    vb = '价格分析'
    if len(stu) != 0:
        return render(request, 'teacher/price.html',
                      {'zd': '客户端', 'vb': vb, 'name': stu, 'city': city, 'imgurl': 'static/img/meng.png'})
    else:
        return render(request, 'teacher/login1.html', {'error': '请登陆'})
def jgtongj(request):
    name = request.session.get("name")
    teacheruser = Teacher.objects.filter(tname=name).first()
    id=request.GET['id']
    if teacheruser != None:
        print("%%%%%%%",id)
        sql1="select sum(" \
             "case when price<1000 then 1 else 0 end)as '1000' ," \
             "sum(case when price>1000 and price<1500 then 1 else 0 end)as '1000-1500'," \
             "sum(case when price>1500 and price<2500 then 1 else 0 end)as '1500-2500'," \
             "sum(case when price>2500 and price<3500 then 1 else 0 end)as '2500-3500'," \
             "sum(case when price>3500 and price<4500  then 1 else 0 end)as '3500-4500' ," \
             "sum(case when price>4500 and price<5500  then 1 else 0 end)as '4500-5500' ," \
             "sum(case when price>5500 and price<6500  then 1 else 0 end)as '5500-6500' ," \
             "sum(case when price>6500   then 1 else 0 end)as '6500' ," \
             "twoj " \
             "from gj where onej='{0}' group by twoj".format(id)
        list2=mysqlhe.get_all(sql1)

        aniu=['<1000','1000-1500','1500-2500','2500-3500','3500-4500','4500-5500','5500-6500','6500<']
        hz=[]
        l=[]
        l1 = []
        l2 = []
        l3 = []
        l4 = []
        l5 = []
        l6 = []
        l7 = []
        print(list2)
        for i in list2:
            l.append(int(i[0]))
            l1.append(int(i[1]))
            l2.append(int(i[2]))
            l3.append(int(i[3]))
            l4.append(int(i[4]))
            l5.append(int(i[5]))
            l6.append(int(i[6]))
            l7.append(int(i[7]))
            hz.append(i[8])
        countlist=[]
        countlist.append(l)
        countlist.append(l1)
        countlist.append(l2)
        countlist.append(l3)
        countlist.append(l4)
        countlist.append(l5)
        countlist.append(l6)
        countlist.append(l7)

        data = {'hz':hz,'aniu':aniu,'countlist':countlist}
        return HttpResponse(json.dumps(data))
    else:
        return render(request, 'teacher/login1.html', {'error': '请登陆'})
def sjgl(request):

    stu = request.session.get("stu")



    vb = '数据管理'

    if len(stu) != 0:

        # onej = request.GET['onej']
        if ('onej' in request.GET):
            onej = request.GET['onej']
        else:
            onej='北京'
        if('lx' in request.GET):
            lx = request.GET['lx']
        else:
            lx = '2室1厅1卫'
        if ('gjc' in request.GET):
            gjc1= request.GET['gjc']
            gjc=' and name like "%{0}%"'.format(gjc1)
        else:
            gjc = ''
        if ('jg' in request.GET):
            jg=request.GET['jg']
            if jg=='0':
                jgsql='and price<3000'
            elif jg=='1':
                jgsql = 'and 3000<price and price<6000'
            elif jg=='2':
                jgsql = 'and price>6000'


        else:
            jgsql=''
        listsql='select * from gj where onej="{0}" and hx="{1}"'.format(onej,lx)+gjc+jgsql
        print('listsql',listsql)
        hosue = mysqlhe.get_all(listsql)

        lxsql='select hx from gj where onej="{0}"  group by hx'.format(onej)

        lx2=mysqlhe.get_all(lxsql)
        lxlist=[]
        for i in lx2:
            lxlist.append(i[0])
        city1 = mysqlhe.get_all('select COUNT(*)as num ,onej from gj  group by onej ')
        city = []
        for i in city1:
            city.append(i[1])
        return  render(request, 'teacher/sjgl.html',
               {'zd': '客户端', 'vb': vb, 'name': stu, 'city': city,'lxlist':lxlist, 'house': hosue})

    else:
        return render(request, 'teacher/login1.html', {'error': '请登陆'})
def zb(request):
    stu = request.session.get("stu")
    # id = request.GET['id']
    if len(stu) != 0:
        vb = '占比分析'
        if ('onej' in request.GET):
            onej = request.GET['onej']
        else:
            onej='北京'

        city1 = mysqlhe.get_all('select COUNT(*)as num ,onej from gj  group by onej ')
        city = []
        for i in city1:
            city.append(i[1])
        return render(request, 'teacher/zb.html',
                      {'zd': '', 'vb': vb, 'name': stu, 'city': city})
    else:
        return render(request, 'teacher/login1.html', {'error': '请登陆'})
def zbtongj(request):
    name = request.session.get("name")
    teacheruser = Teacher.objects.filter(tname=name).first()
    id = request.GET['id']
    if teacheruser != None:
        twojsql=mysqlhe.get_all('select twoj from gj where onej="{0}" group by  twoj'.format(id))
        print(twojsql)
        twojlist=[]
        for i in twojsql:
            twojlist.append(i[0])
        data={"twojlist":twojlist}
        return HttpResponse(json.dumps(data))

    else:
        return render(request, 'teacher/login1.html', {'error': '请登陆'})
def sjfk(request):
    stu=request.session.get('stu')
    if request.method == 'POST':
        tid = request.POST['user_name']
        tzh = request.POST['id']
        tname = request.POST['nr']
        print('##############')
        fksql="insert into fk (bt,text,useid) values('{0}','{1}','{2}')".format(tid,tname,tzh)
        mysqlhe.insert(fksql)

        return render(request, 'teacher/sjfk.html', {'jg': '反馈成功','name':stu})

    else:
        return render(request, 'teacher/sjfk.html',{'name':stu})
def fklb(request):
    stu=request.session.get('stu')

    sql="select * from fk"
    lisat=mysqlhe.get_all(sql)
    print(lisat)
    return render(request, 'teacher/fklb.html',{'house':lisat,'name':stu})
def loout(request):
    request.session.flush()
    return render(request,'teacher/login1.html')
def grzx(request):
    vb = '个人中心'
    stu = request.session.get('stu')

    return render(request, 'teacher/grzx.html',{'vb': vb,'name':stu})
